package com.fh.callService;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import javax.xml.rpc.ServiceException;
import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class TestMainCall {

    public static void main(String[] args) throws ServiceException, RemoteException {
        //接口测试
//        UncallWorld();
        //点击拨号
        OnClickCall();
        //获取录音文件名
//        getRecording();
    }

    /**
     * 接口测试
     * @throws ServiceException
     * @throws RemoteException
     */
    private static void UncallWorld() throws ServiceException, RemoteException {
        System.out.println(getCall().uncallWorld("电话测试"));
    }

    /**
     * 点击拨号
     * @throws ServiceException
     * @throws RemoteException
     */
    private static void OnClickCall() throws ServiceException, RemoteException {
        System.out.println(getCall().onClickCall("830","015806122912","2017ABC"));
    }
    /**
     * 获取录音文件名
     * @throws ServiceException
     * @throws RemoteException
     */
    private static void getRecording() throws ServiceException, RemoteException {
        UncallAPIBindingStub call = getCall();
        Map callStatus = getNodeMap(call.popEvent("830"));
        String uid = getNodeMap(call.popEvent("830")).get("uid");
        System.out.println("呼叫的类型: " + callStatus);
        System.out.println("uid: " + uid);
        System.out.println(call.getExtenStatus ("830"));
        System.out.println(call.getRecording(uid));
//        System.out.println(call.getRecording("1503022543"));
    }

    /**
     * 将xml解析成map类型
     * @param xml （String）
     * @return
     */
    public static Map<String,String> getNodeMap(String xml) {
        Map<String, String> map = new HashMap<>();
        try {
            Document doc =  DocumentHelper.parseText(xml);//将xml转为dom对象
            Element root = doc.getRootElement();//获取根节点
            readEle(root,map);
        }catch (DocumentException e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 递归xml
     * @param e
     * @param map
     */
    public static void readEle(Element e,Map<String, String> map){
        //判断是否有复合内容
        if(e.hasMixedContent()){
            System.out.println("父节点名称:" + e.getName());
            Iterator it = e.elementIterator();
            while (it.hasNext()) {
                e = (Element) it.next();
                //递归
                readEle(e,map);
            }
        }else{
            map.put(e.getName(), e.getTextTrim());//获取所有没有子节点的节点  =》 key和value
        }
    }

    private static UncallAPIBindingStub getCall() throws ServiceException {
        UncallAPILocator service = new UncallAPILocator();
        return (UncallAPIBindingStub) service.getUncallAPIPort();
    }
}
